package dao.impl;

import dao.StudentDao;
import entity.Student;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.qf.utils.DruidUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/*
杨威
2021/9/7
19:31
*/
public class StudentDaoImpl implements StudentDao {
    QueryRunner queryRunner = new QueryRunner();
    @Override
    public int insert(Student student) {
        try {
            String sql ="insert into student(stuName,stuGender,stuPhone,bornDate,stuEmail,stuAddress,gradeId) values(?,?,?,?,?,?,?);";
            Object[] params = {student.getStuName(), student.getStuGender(), student.getStuPhone(), student.getBornDate(), student.getStuEmail(), student.getStuAddress(), student.getGradeId()};
            return queryRunner.update(DruidUtil.getConnection(),sql,params);//和上午写的commonsUpdate一个道理
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"插入出现异常");
        }
    }

    @Override
    public int update(Student student) {
        try {
            String sql="update student set stuName=?,stuGender=?,stuPhone=?,bornDate=?,stuEmail=?,stuAddress=?,gradeId=? where stuId=?";
            Object[] params={student.getStuName(),student.getStuGender(),student.getStuPhone(),student.getBornDate(),student.getStuEmail(),student.getStuAddress(),student.getGradeId(),student.getStuId()};
            return queryRunner.update(DruidUtil.getConnection(),sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"修改出现异常");
        }
    }

    @Override
    public int delete(int id) {
        try {
            String sql="delete from student where stuId=?";
            return queryRunner.update(DruidUtil.getConnection(),sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"删除出现异常");
        }
    }

    @Override
    public Student selectOne(int stu_id) {
        try {
            String sql="select * from student where stuId=?";
            Connection connection = DruidUtil.getConnection();
            System.out.println(connection);
            return queryRunner.query(connection,sql,new BeanHandler<>(Student.class),stu_id);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"查询单个出现异常");
        }
    }


    @Override
    public List<Student> selectAll() {
        try {
            String sql="select * from student";
            Connection connection = DruidUtil.getConnection();
            System.out.println(connection);
            List<Student> query = queryRunner.query(connection, sql, new BeanListHandler<>(Student.class));
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage()+"查询单个出现异常");
        }

    }
}
